<?php

namespace Aiweline\AiReviewForMagentoProduct\Lib;

use \ArdaGnsrn\Ollama\Ollama;

class ReviewGeneration
{
    static public function generate(string $input, string $host='http://localhost:11434',string $model = 'deepseek-r1:1.5b', int &$retry = 1)
    {
        // Initialize the Ollama client
        $client = \ArdaGnsrn\Ollama\Ollama::client($host);

        // Prepare the request payload
        $payload = [
            'model' => $model, // Replace with your actual model name
            'prompt' => $input,
            'temperature' => 0.7,
            'timeout' => 60,
        ];

        // Send the request to the Ollama platform
        $completions = $client->completions()->create($payload);
        $response = $completions->response;
        # 正则提取think标签内容
        preg_match('/<think\b[^>]*>(.*?)<\/think>/is', $response, $matches);
        $think = $matches[1] ?? '';
        # 去除think标签
        $response = preg_replace('/<think\b[^>]*>(.*?)<\/think>/is', '', $response);
        $response = str_replace('```json', '', $response);
        $response = str_replace('```', '', $response);
        $response = str_replace("\r\n", "\n", $response);
        $response = str_replace("\n", '', $response);
        $response = json_decode($response, true);
        if (!$response) {
            if ($retry) {
                $retry--;
                d('重试次数：' . $retry);
                $input .= PHP_EOL . 'json格式不正确,无法解析，请重新按照要求生成！';
                return self::generate($input, $model, $retry);
            }
            return false;
        }
//        $response['think'] = $think;
//        $response['input'] = $input;
        return $response;
    }
}